import { Directive, Input, Optional, TemplateRef, ViewContainerRef, Renderer2, ElementRef, OnInit } from '@angular/core';

import { AclService } from '../../core/service/acl.service';

@Directive({
  selector: '[bzAcl]'
})
export class AclDirective<B, S> implements OnInit {

  @Input() bzAcl: string;

  constructor(
    @Optional() private templateRef: TemplateRef<null>,
    private renderer: Renderer2,
    private viewContainerRef: ViewContainerRef,
    private ele: ElementRef,
    private aclService: AclService<B, S>
  ) { }

  ngOnInit(): void {
    const _show = this.aclService.includeAclCode(this.bzAcl);

    // 根据使用方式（结构性指令或者属性型指令）的不同，用不同的方式处理隐藏显示
    if (this.templateRef) {
      if (_show) {
        this.viewContainerRef.createEmbeddedView(this.templateRef, null);
      } else {
        this.viewContainerRef.clear();
      }
    } else {
      if (_show) {
        this.renderer.removeAttribute(this.ele.nativeElement, 'hidden');
      } else {
        this.renderer.setAttribute(this.ele.nativeElement, 'hidden', '');
      }
    }

  }

}
